#include "graphics.h"

void init_graphics() {
    render_changed = 0;

    window = SDL_CreateWindow(
        WINDOW_TITLE,
        /* initial pos of window */
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        /* window scale */
        WINDOW_W, WINDOW_H,
        /* show immediately */
        SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI
    );

    if (window == NULL) {
        fprintf(stderr, "SDL_CreateWindow error: %s\n", SDL_GetError());
        exit(1);
    }

    /* creates renderer
       -1 specifies the loading of whichever video driver supports our flags
       SDL_RENDERER_ACCELERATED:  use hardware accelerating
       SDL_RENDERER_PRESENTVSYNC: synchronize present function (update display) with monitor refresh rate
    */
    render = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE);

    if (render == NULL) {
        fprintf(stderr, "SDL_CreateRenderer error: %s\n", SDL_GetError());
        exit(-1);
    }

    SDL_SetRenderDrawBlendMode(render, SDL_BLENDMODE_BLEND);

    /* texture for render context */
    display = SDL_CreateTexture(render, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, WINDOW_W, WINDOW_H);

    SDL_SetRenderTarget(render, display);
}

void set_render_changed() {
    render_changed = 1;
}

void pre_render() {
    SDL_SetRenderTarget(render, display);
}

void update_render() {
    if (render_changed) {
        SDL_SetRenderTarget(render, NULL);
        SDL_RenderCopy(render, display, NULL, NULL);

        SDL_RenderPresent(render);
        render_changed = 0;
    }
}

void cleanup_graphics() {
    SDL_DestroyRenderer(render);
    SDL_DestroyWindow(window);
}

void draw_rect(int x, int y, int w, int h) {
    SDL_Rect bg = { x, y, w, h };
    SDL_RenderDrawRect(render, &bg);
    set_render_changed();
}

void draw_img(char *file, SDL_Rect* dstrect) {
    display = IMG_LoadTexture(render, file);
    if (display == NULL) {
        fprintf(stderr, "draw_img error: %s\n", SDL_GetError());
        exit(1);
    }
    if (SDL_SetTextureBlendMode(display, SDL_BLENDMODE_BLEND)) {
        fprintf(stderr, "draw_img error: %s\n", SDL_GetError());
        exit(1);
    }

    SDL_Rect srcrect = { 0, 0, WINDOW_W, WINDOW_H };
    SDL_RenderCopy(render, display, &srcrect, dstrect);
    set_render_changed();
}
